package com.myapp.web.struts2.validators;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
import com.google.code.kaptcha.Constants;

//com.opensymphony.xwork2.validator.validators.RequiredFieldValidator

public class KaptchaFieldValidator extends FieldValidatorSupport {

	private String emptyMessage;
	
	private boolean isEmpty = false;
	
	@Override
	public void validate(Object object) throws ValidationException {
		String fieldName = getFieldName();
		String value = (String)getFieldValue(fieldName, object);
		
		if(value == null || value.trim().length() == 0 )
		{
			isEmpty = true;
			addFieldError(fieldName, object);
			return ;
		}
		String kaptchaValue =(String)ActionContext.getContext().getSession().get(Constants.KAPTCHA_SESSION_KEY);
		System.out.println("kaptcha****************" + kaptchaValue);
		if(!kaptchaValue.equalsIgnoreCase(value))
		{
			addFieldError(fieldName, object);
		}
	}

	@Override
	public String getMessage(Object object)
	{
		if(isEmpty && !emptyMessage.isEmpty())
		{
			return emptyMessage;
		}
		return super.getMessage(object);
	}
	
	public String getEmptyMessage() {
		return emptyMessage;
	}

	public void setEmptyMessage(String emptyMessage) {
		this.emptyMessage = emptyMessage;
	}	
}
